﻿using System;
using System.Globalization;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using YogaStudio.Data.Domain;
using YogaStudio.Service.BLL;
using YogaStudio.WebUI.Helper;
using YogaStudio.WebUI.Infrastructure;
using YogaStudio.WebUI.Interfaces;
using YogaStudio.WebUI.Models;
using YogaStudio.WebUI.Services;



namespace YogaStudio.WebUI.Controllers
{
    public class AccountController : Controller
    {
        public IMembershipService MembershipService { get; set; }
        private readonly IUserManagementService _userManagementService = new UserManagementService();
        private readonly IShoppingCartService _shoppingCartService = new ShoppingCartService();
    

        protected override void Initialize(RequestContext requestContext)
        {
            if (MembershipService == null) { MembershipService = new AccountMembershipService(new CustomMembershipProvider()); }

            base.Initialize(requestContext);
        }

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    //SetupFormsAuthTicket(model.UserName, model.RememberMe);
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    MigrateShoppingCart(model.UserName);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }

            return View(model);
        }

        private void MigrateShoppingCart(string userName)
        {
            _shoppingCartService.SetCartId(HttpContext);

            _shoppingCartService.MigrateCart(userName);
            Session[ShoppingCartService.CartSessionKey] = userName;
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                var createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

          
                if (createStatus == MembershipCreateStatus.Success)
                {
                    var currentUser = _userManagementService.GetUser(model.UserName);
                    _userManagementService.AddUserRole(new UserRole
                    {
                        UserId = currentUser.UserId,
                        RoleId = 3
                    });
                    EmailSender email = new EmailSender();
                    StringBuilder msg = new StringBuilder("<b>Congratulations! Welcome to our website</b>");
                    msg.Append("We are here to serve you!");
                    email.PrepareMail(model.Email, model.UserName, msg);

                    return RedirectToAction("LogOn", "Account");
                

                }
                ModelState.AddModelError("", ErrorCodeToString(createStatus));
            }

            return View(model);
        }

        [Authorize(Roles="Admin")]
        public ActionResult RegisterFaculty(int id)
        {
            ViewBag.FacultyId = id;
            return View("Register");
        }

        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult RegisterFaculty(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                var createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);


                if (createStatus == MembershipCreateStatus.Success)
                {
                    var currentUser = _userManagementService.GetUser(model.UserName);
                    _userManagementService.AddUserRole(new UserRole
                    {
                        UserId = currentUser.UserId,
                        RoleId = 2
                    });
                    EmailSender email = new EmailSender();
                    StringBuilder msg = new StringBuilder("<b>Welcome! Faculty Member account is opened for you</b>");
                    msg.Append("Your account is: <br>User Name="+model.UserName+" </br><br>Password="+model.Password+"</br><br></br>");
                    email.PrepareMail(model.Email, model.UserName, msg);

                    
                    IFacultySerivce factuService=new FacultySerivce();
                    int facultyId = Int32.Parse(model.FacultyId.ToString());
                    Faculty faculty = factuService.GetFaculty(facultyId);
                    faculty.UserId = currentUser.UserId;

                    factuService.UpdateFaculty(faculty);

                    return RedirectToAction("Index", "Faculties");

                }
                ModelState.AddModelError("", ErrorCodeToString(createStatus));
            }
            ViewBag.FacultyId = model.FacultyId;
            return View("Register", model);
        }
   
   
        public ActionResult Confirm(string userName)
        {
            UserManagementService userManagement=new UserManagementService();
            User user = userManagement.GetUser(userName);
            if (user != null)
            {
                user.isConfirmed = true;
                userManagement.ConfirmUserRegistration(user);
            }

            return RedirectToAction("Index", "Home");
        }

        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ForgotPassword(ForgotPassword model)
        {
            ViewBag.Exception = "";
            if (ModelState.IsValid)
            {
                try
                {
                    var newPassword = MembershipService.ForgotPassword(model.UserName);
                    var user = _userManagementService.GetUser(model.UserName);
                    EmailSender email = new EmailSender();
                    StringBuilder msg = new StringBuilder("<span style=\"color:black;\"><br/> Your password has been reset to new password.<br/>" +
                                                          "your new password is: <b>"+newPassword+" </b></span><br/>");

                    email.ForgotPasswordEmail(user.UserEmailAddress, model.UserName, msg);


                    return View("ForgotPasswordSuccess");
                }
                catch (Exception exception)
                {
                    TempData["Message"] = exception.Message;
                    return Redirect("ForgotPassword");
                }

            }
            return null;
        }

        public ActionResult ForgotPasswordSuccess()
        {
           return View();
        }

        [Authorize]
        public ActionResult PasswordChange()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult PasswordChange(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                bool changePasswordSucceeded = false;
                try
                {
                   
                        changePasswordSucceeded = MembershipService.ChangePassword(User.Identity.Name,model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            return View(model);
        }

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        private void SetupFormsAuthTicket(string userName, bool persistanceFlag)
        {
            User user = _userManagementService.GetUser(userName);
            var userId = user.UserId;
            var userData = userId.ToString(CultureInfo.InvariantCulture);
            var authTicket = new FormsAuthenticationTicket(1, //version
                                                        userName, // user name
                                                        DateTime.Now,             //creation
                                                        DateTime.Now.AddMinutes(30), //Expiration
                                                        persistanceFlag, //Persistent
                                                        userData);

            var encTicket = FormsAuthentication.Encrypt(authTicket);
            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
            return;
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
